#pragma once

#include <ctime>
#include <sstream>
#include <string_view>
#include <unordered_map>

#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/mman.h>

#include "Buffer.h"
#include "Common.h"
#include "HTTPRequest.h"

class HTTPResponse {
private:
    HTTP_CODE code;
    std::string path;
    std::string root_path;

    char *file;
    struct stat file_state;

    std::time_t now;

    std::stringstream ss;
    const static std::string_view CRLF;

    const std::unordered_map<HTTP_CODE, std::string> STATUS_CODE = {  // 状态码和描述的映射
            {CONTINUE,              "Continue"},
            {OK,                    "OK"},
            {BAD_REQUEST,           "Bad Request"},
            {FORBIDDEN,             "Forbidden"},
            {NOT_FOUND,             "Not Found"},
            {INTERNAL_SERVER_ERROR, "Internal Server Error"}
    };

    const std::unordered_map<std::string_view, std::string> SUFFIX_TYPE = {  // 文件扩展名和Content-type映射
            {".html",  "text/html"},
            {".xml",   "text/xml"},
            {".xhtml", "application/xhtml+xml"},
            {".txt",   "text/plain"},
            {".rtf",   "application/rtf"},
            {".pdf",   "application/pdf"},
            {".word",  "application/nsword"},
            {".png",   "image/png"},
            {".gif",   "image/gif"},
            {".jpg",   "image/jpeg"},
            {".jpeg",  "image/jpeg"},
            {".au",    "audio/basic"},
            {".mpeg",  "video/mpeg"},
            {".mpg",   "video/mpeg"},
            {".avi",   "video/x-msvideo"},
            {".gz",    "application/x-gzip"},
            {".tar",   "application/x-tar"},
            {".css",   "text/css"},
            {".js",    "text/javascript"},
    };

    void error_page(HTTP_CODE error_code, Buffer &buffer);  // 处理错误生成页面

public:
    HTTPResponse();

    ~HTTPResponse();

    char *get_file() const;

    size_t get_file_length() const;

    void generate_response(const HTTPRequest &request, Buffer &buffer);  // 生成响应报文，buffer是传出参数

};

